import CIcdConfigAPI, { type CicdConfigVO } from "@/api/build/cicdConfig";
import { store } from "@/store";

export const useDevopsStore = defineStore("devops", () => {
  const configs = ref<CicdConfigVO[]>([]);
  const isLoading = ref(false);

  const selectedCicdConfigId = useStorage<number | undefined>("selectedCicdConfigId", undefined);
  const selectedNamespace = useStorage<string | undefined>("selectedNamespace", undefined);
  const availableNamespaces = ref<string[]>([]);

  const currentConfig = computed(() => {
    return configs.value.find((c) => c.id === selectedCicdConfigId.value);
  });

  const isK8s = computed(() => currentConfig.value?.deployType === "k8s");

  async function loadConfigs() {
    if (isLoading.value) return;
    isLoading.value = true;
    try {
      const list = await CIcdConfigAPI.getList();
      configs.value = (list || []).filter((c) => c && c.id != null);
      // 如果没有选择且存在配置，默认不自动选中，交由用户选择
    } finally {
      isLoading.value = false;
    }
  }

  function setSelectedConfigId(id?: number) {
    selectedCicdConfigId.value = id;
    // 切换配置时同步命名空间默认值
    const conf = configs.value.find((c) => c.id === id);
    if (conf?.nameSpace) {
      selectedNamespace.value = conf.nameSpace;
    } else {
      selectedNamespace.value = undefined;
    }
    // 切换配置时清空可选命名空间，等待页面重新加载
    availableNamespaces.value = [];
  }

  function setSelectedNamespace(ns?: string) {
    selectedNamespace.value = ns;
  }

  function setAvailableNamespaces(list: string[]) {
    // 去重并排序
    const unique = Array.from(new Set(list.filter(Boolean)));
    availableNamespaces.value = unique.sort();
    // 如果当前选择不在列表中，则重置
    if (selectedNamespace.value && !unique.includes(selectedNamespace.value)) {
      selectedNamespace.value = unique[0];
    }
  }

  return {
    // state
    configs,
    isLoading,
    selectedCicdConfigId,
    selectedNamespace,
    availableNamespaces,
    // getters
    currentConfig,
    isK8s,
    // actions
    loadConfigs,
    setSelectedConfigId,
    setSelectedNamespace,
    setAvailableNamespaces,
  };
});

export function useDevopsStoreHook() {
  return useDevopsStore(store);
}
